package com.bjh.client;

import cn.hutool.json.JSONUtil;
import com.bjh.model.Message;
import com.bjh.model.MessageBody;
import com.bjh.model.MessageHead;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.ArrayList;
import java.util.List;

public class ClientHandler extends SimpleChannelInboundHandler<Message> {


    ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 当客户端连接服务器完成就会触发该方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        for(int i = 0; i < 20; i ++) {
            Message message = new Message();
            MessageHead messageHead = new MessageHead();
            messageHead.setCommond(9988);
            messageHead.setMessageType(0x0);
            messageHead.setClientType(1);
            messageHead.setVersion(2);
            messageHead.setAppId(3);

            String msg = "hello-" + i;
            messageHead.setBodyLen(msg.getBytes().length);
            String imei = "12-euri";
            messageHead.setImeiLen(imei.getBytes().length);

            List<String> paramsTypes = new ArrayList<>();
            paramsTypes.add("java.lang.Integer");
            paramsTypes.add("java.lang.String");
            try {
                messageHead.setParamsTypeLen(objectMapper.writeValueAsString(paramsTypes).getBytes().length);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            MessageBody messageBody = new MessageBody();
            messageBody.setImei(imei);
            messageBody.setData(msg);
            messageBody.setParams(paramsTypes);
            message.setMessageHead(messageHead);
            message.setMessageBody(messageBody);
            ctx.writeAndFlush(message);
        }
    }





    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    //当通道有读取事件时会触发，即服务端发送数据给客户端
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Message message) throws Exception {
        System.out.println(JSONUtil.toJsonPrettyStr(message));
    }
}
